package com.lx.huimailf.fragment.backorder;


import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lx.huimailf.R;
import com.lx.huimailf.adapter.BackGoodsAdapter;
import com.lx.huimailf.adapter.LinkerStatusAdapter;
import com.lx.huimailf.adapter.PubAdapter;
import com.lx.huimailf.configs.Config;
import com.lx.huimailf.fragment.BackGoodsFragment;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class BackDetialFragment extends Fragment {
    private TextView orderno,name,phone,address,peisongStatus;
    private TextView payMethod,psTime,getTime,allMoney,realMoney,createTime;

    private RecyclerView recyclerView;
    private String orderNo="";
    private String exiteno="";
    private String Id="";
    private String custid="";
    private String status="0";
    private Button shenhe;
    AlertDialog dialog;
    private String linkerstatus;


    private RelativeLayout rpayMethod;
    private LinearLayout sendTime,finishTime;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_order_detial, container, false);
        initViews(view);
        SharedPreferences sp=getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        custid=sp.getString("custid","-11111");
        orderNo=getActivity().getIntent().getStringExtra("orderno");
        exiteno=getActivity().getIntent().getStringExtra("exiteno");
        Id=getActivity().getIntent().getStringExtra("id");
        status=getActivity().getIntent().getStringExtra("status");
        linkerstatus=getActivity().getIntent().getStringExtra("linkerstatus");

        if(status.equals("-1")){
            peisongStatus.setText("未分配配送员");
        }else if(status.equals("0")){
            peisongStatus.setText("等待退货");
            if (linkerstatus.equals("0")){
                shenhe.setVisibility(View.VISIBLE);
            }


        }else if(status.equals("1")){
            peisongStatus.setText("退货完成");
        }else if(status.equals("2")){
            peisongStatus.setText("退货中");
        }

        getOrderInfoByOrderno();
        return view;
    }

    private void initViews(View view){

        recyclerView=(RecyclerView)view.findViewById(R.id.recyclerview);
        orderno=(TextView)view.findViewById(R.id.orderno);
        name=(TextView)view.findViewById(R.id.xingming);
        phone=(TextView)view.findViewById(R.id.phone);
        address=(TextView)view.findViewById(R.id.tv3);
        orderno=(TextView)view.findViewById(R.id.orderno);
        peisongStatus=(TextView)view.findViewById(R.id.tv_status);

        payMethod=(TextView)view.findViewById(R.id.ps_method);
        psTime=(TextView)view.findViewById(R.id.ps_time);
        getTime=(TextView)view.findViewById(R.id.get_time);
        allMoney=(TextView)view.findViewById(R.id.allprice);
        realMoney=(TextView)view.findViewById(R.id.realmoney);
        createTime=(TextView)view.findViewById(R.id.createtime);
        shenhe=(Button) view.findViewById(R.id.shenhe);
        shenhe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upLinkerStatus();
            }
        });

        rpayMethod=(RelativeLayout)view.findViewById(R.id.rll5);
        sendTime=(LinearLayout) view.findViewById(R.id.rll6);
        finishTime=(LinearLayout)view.findViewById(R.id.rll7);
        rpayMethod.setVisibility(View.GONE);
        sendTime.setVisibility(View.GONE);
        finishTime.setVisibility(View.GONE);

    }


    private void getExitIfnoById(){
        HashMap<String,String> map=new HashMap<>();
        map.put("id",Id);
        Gson gson=new Gson();
        String parmas=gson.toJson(map);
        OkHttpUtils
                .post()
                .url(Config.url+"send/searchExiteOrderDetail.do")
                .addParams("data",parmas)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONArray jsonArray=null;
                        JSONObject jsonObject=null;
                        ArrayList<HashMap<String,Object>> mapArrayList=new ArrayList<HashMap<String, Object>>();

                        try {
                            jsonArray=new JSONArray(response);
                            for (int i=0;i<jsonArray.length();i++){
                                HashMap<String,Object> map1=new HashMap<String, Object>();
                                jsonObject=jsonArray.getJSONObject(i);
                                map1.put("price",jsonObject.getString("saleprice"));
                                map1.put("proname",jsonObject.getString("proname"));
                                map1.put("count",jsonObject.getString("exitecount"));
                                map1.put("picname", Config.url+"tmp/"+jsonObject.getString("picname"));
                                mapArrayList.add(map1);
                            }
                            PubAdapter myAdapter=new PubAdapter(getContext(),mapArrayList);
                            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                            recyclerView.setAdapter(myAdapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }


    /**
     * 通过订单号获取商品信息
     */
    private void getOrderInfoByOrderno(){
        HashMap<String,String> map=new HashMap<>();
        map.put("exiteno",exiteno);
        map.put("page","1");
        map.put("rows","1");
        Gson gson=new Gson();
        String parmas=gson.toJson(map);
        OkHttpUtils
                .post()
                .url(Config.url+"send/searchExiteOrder.do")
                .addParams("data",parmas)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        getExitIfnoById();
                        JSONArray jsonArray=null;
                        JSONObject jsonObject=null;

                        try {
                            jsonArray=new JSONArray(response);

                            for (int i=0;i<jsonArray.length();i++){
                                jsonObject=jsonArray.getJSONObject(i);

                                orderno.setText(jsonObject.getString("exiteno"));
                                name.setText(jsonObject.getString("custname"));
                                if(jsonObject.getString("custphone").equals("null")){
                                    phone.setText("");
                                }
                                phone.setText(jsonObject.getString("custphone"));

                                address.setText(jsonObject.getString("exiteaddress"));

                                psTime.setText("");
                                getTime.setText("");
                                allMoney.setText(jsonObject.getString("exitmoney"));
                                realMoney.setText(jsonObject.getString("exitmoney"));
                                createTime.setText(getTime(jsonObject.getString("createtime")));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private String getTime(String time){
        if(!time.equals("null")){
            Date date=new Date(Long.valueOf(time));
            SimpleDateFormat format;
            format=new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return format.format(date);
        }else {
            return "";
        }
    }

    /**
     * 显示审核列表和提交审核状态
     */
    private void upLinkerStatus(){
        ArrayList<HashMap<String,String>> mList=new ArrayList<>();
        HashMap<String,String> map1=new HashMap<>();
        map1.put("name","拒绝");
        map1.put("posi","-1");
        mList.add(map1);
        HashMap<String,String> map2=new HashMap<>();
        map2.put("name","待定");
        map2.put("posi","0");
        mList.add(map2);
        HashMap<String,String> map3=new HashMap<>();
        map3.put("name","通过");
        map3.put("posi","1");
        mList.add(map3);
        View layout = LayoutInflater.from(getContext()).inflate(R.layout.dialog_recyclerview_city, null, false);

        RecyclerView mReceAddrRecyclerView=(RecyclerView)layout.findViewById(R.id.rv_people);

        LinkerStatusAdapter xiaoquAdapter=new LinkerStatusAdapter(getContext(),mList);
        mReceAddrRecyclerView.setAdapter(xiaoquAdapter);
        mReceAddrRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        final AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
        builder1
                .setTitle("")
                .setView(layout);
        dialog=builder1.create();
        dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        dialog.show();

        xiaoquAdapter.setOnItemClickLitener(new LinkerStatusAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position, String posi) {
                upStatus(orderNo,exiteno,posi);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
    }

    /**
     * 提交审核状态
     */
    private void upStatus(String orderno, String exiteno,String position){

        HashMap<String,String> map=new HashMap<>();
        map.put("linkerstatus",position);
        map.put("orderno",orderno);
        map.put("exiteno",exiteno);
        Gson gson=new Gson();
        String parmas=gson.toJson(map);
        OkHttpUtils
                .post()
                .url(Config.url+"distribute/confirmExiteOrder.do")
                .addParams("data",parmas)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if(response.equals("true")){
                            BackGoodsFragment.getBackGoodsInfo();
                            dialog.dismiss();
                            Toast.makeText(getContext(),"审核状态改变",Toast.LENGTH_SHORT).show();
                        }

                    }
                });
    }
}
